<template>
  <div class="id-photo-view min-h-screen bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-2xl font-bold text-gray-900">证件照生成</h1>
        <p class="mt-2 text-sm text-gray-600">上传照片，选择参数，一键生成标准证件照</p>
      </div>

      <div class="space-y-8">
        <!-- 第一栏：上传区域和参数设置区域 -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
          <!-- 上传区域 -->
          <div class="bg-white rounded-lg shadow-sm p-6 flex items-center h-[550px]">
            <div
                class="my-auto border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-indigo-500 transition-colors duration-200 relative w-full h-full flex items-center justify-center"
                :class="[
                { 'border-indigo-500': isDragging },
                previewUrl ? '!border-0 !p-0' : ''
              ]"
                @dragover.prevent="handleDragOver"
                @dragleave.prevent="handleDragLeave"
                @drop.prevent="handleDrop"
            >
              <!-- 上传状态 -->
              <div v-if="!previewUrl" class="space-y-4 w-full">
                <svg class="mx-auto h-16 w-16 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48">
                  <path
                      d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                      stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
                <div class="text-sm text-gray-600 mb-0.5">
                  <label for="file-upload"
                         class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
                    <span>上传照片</span>
                    <input
                        id="file-upload"
                        type="file"
                        class="sr-only"
                        accept="image/*"
                        @change="handleFileChange"
                    >
                  </label>
                  <p class="pl-1 mt-2.5">或将图片拖放到这里</p>
                </div>
                <p class="text-xs text-gray-500">支持 JPG、PNG 格式，大小不超过 1MB</p>
              </div>

              <!-- 预览状态 -->
              <div v-else class="relative w-full h-full">
                <!-- 关闭按钮 -->
                <button
                    @click="clearPreview"
                    class="absolute top-2 right-2 z-10 p-1 bg-white bg-opacity-80 rounded-full hover:bg-opacity-100 transition-all duration-200"
                >
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 384 512"
                       class="h-4 w-4 text-gray-600 hover:text-gray-800">
                    <path
                        d="M342.6 150.6c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L192 210.7 86.6 105.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3L146.7 256 41.4 361.4c-12.5 12.5-12.5 32.8 0 45.3s32.8 12.5 45.3 0L192 301.3 297.4 406.6c12.5 12.5 32.8 12.5 45.3 0s12.5-32.8 0-45.3L237.3 256 342.6 150.6z"/>
                  </svg>
                </button>

                <!-- 预览图片 -->
                <div class="aspect-w-4 aspect-h-3 overflow-hidden rounded-lg h-full">
                  <img :src="previewUrl" alt="预览图" class="w-full h-full object-contain mx-auto">
                </div>
              </div>
            </div>
          </div>

          <!-- 参数设置区域 -->
          <div class="bg-white rounded-lg shadow-sm p-6 h-[550px] flex flex-col">
            <!-- Tab切换 -->
            <div class="border-b border-gray-200 mb-6">
              <nav class="-mb-px flex space-x-8">
                <button
                    @click="activeTab = 'core'"
                    :class="[
                    activeTab === 'core'
                      ? 'border-indigo-500 text-indigo-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300',
                    'whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm'
                  ]"
                >
                  基础设置
                </button>
                <button
                    @click="activeTab = 'advanced'"
                    :class="[
                    activeTab === 'advanced'
                      ? 'border-indigo-500 text-indigo-600'
                      : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300',
                    'whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm'
                  ]"
                >
                  高级参数
                </button>
              </nav>
            </div>

            <div class="flex-1 overflow-y-auto">
              <!-- 基础设置 Tab -->
              <div v-if="activeTab === 'core'" class="h-full">
                <div class="flex justify-between">
                  <!-- 证件照尺寸 -->
                  <div class="space-y-4 w-[450px]">
                    <h4 class="text-md font-medium text-gray-900 mb-4">证件照尺寸</h4>
                    <div class="grid grid-cols-1 gap-3">
                      <label
                          v-for="size in photoSizes"
                          :key="size.value"
                          class="relative flex items-center p-4 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50 transition-colors duration-200"
                          :class="{ 'border-indigo-500 bg-indigo-50': selectedSize === size.value }"
                      >
                        <input
                            type="radio"
                            :value="size.value"
                            v-model="selectedSize"
                            class="sr-only"
                        >
                        <div class="flex items-center justify-between w-full">
                          <div class="flex items-center">
                            <div
                                class="w-4 h-4 border-2 rounded-full mr-3 flex items-center justify-center"
                                :class="selectedSize === size.value ? 'border-indigo-500' : 'border-gray-300'"
                            >
                              <div
                                  v-if="selectedSize === size.value"
                                  class="w-2 h-2 bg-indigo-500 rounded-full"
                              ></div>
                            </div>
                            <span class="text-sm font-medium text-gray-900">{{ size.label }}</span>
                          </div>
                          <span class="text-xs text-gray-500">{{ size.dimensions }}</span>
                        </div>
                      </label>
                    </div>
                  </div>

                  <!-- 背景颜色 -->
                  <div class="space-y-4 w-[220px]">
                    <h4 class="text-md font-medium text-gray-900 mb-4 text-center">背景颜色</h4>
                    <div class="flex flex-col justify-between h-[370px]">
                      <button
                          v-for="color in backgroundColors"
                          :key="color.value"
                          class="w-[53px] h-[53px] rounded-lg focus:outline-none transition-all duration-200 border-2 border-gray-300 mx-auto"
                          :style="{ backgroundColor: color.hexColor }"
                          :class="[
                          selectedColor === color.value ? 'ring-2 ring-offset-2 ring-indigo-500 scale-110' : 'hover:scale-105'
                        ]"
                          @click="selectedColor = color.value"
                      ></button>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 高级参数 Tab -->
              <div v-if="activeTab === 'advanced'" class="flex flex-col relative overflow-hidden h-full">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-medium text-gray-900">高级参数</h3>
                  <span
                      class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-indigo-100 text-indigo-800">
                    VIP 专享
                  </span>
                </div>
                <div class="space-y-6">
                  <div v-for="param in advancedParams" :key="param.name">
                    <div class="flex items-center justify-between mb-2">
                      <label class="block text-sm font-medium text-gray-700">{{ param.label }}</label>
                      <span class="text-sm text-gray-500">{{ param.value }}</span>
                    </div>
                    <input
                        type="range"
                        v-model="param.value"
                        :min="param.min"
                        :max="param.max"
                        class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer"
                    >
                  </div>
                </div>
                <!-- 遮罩层 -->
                <div v-if="!userStore.getLoginUser()?.isVip"
                     class="absolute inset-0 bg-white bg-opacity-95 z-10 flex flex-col items-center justify-center p-6 text-center select-none rounded-lg">
                  <h4 class="text-lg font-semibold text-indigo-700 mb-4">
                    解锁高级参数调节
                  </h4>
                  <p class="text-gray-600 text-sm mb-6 max-w-sm">
                    升级为VIP用户，即可解锁美颜、亮度、对比度、饱和度、锐化等多项细致调节功能，助你获得更完美的证件照效果。
                  </p>
                  <p class="text-gray-600 text-sm mb-10 max-w-sm">
                    心动了吗？立即升级VIP，享受更多高级参数带来的惊喜！点击下方按钮，了解详情！
                  </p>
                  <button
                      class="bg-yellow-400 hover:bg-yellow-500 text-white font-bold py-3 px-6 rounded-lg shadow-md transition-colors duration-200 text-base">
                    立即升级VIP
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 第三栏：生成效果展示 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
          <h2 class="text-xl font-bold text-gray-900 mb-6">生成效果</h2>
          <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-6">
            <!-- 左侧：标准照和高清照 -->
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
              <!-- 标准照 -->
              <div class="border-2 border-dashed border-gray-300 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-medium text-gray-900">标准照</h3>
                  <button
                      class="inline-flex items-center text-sm text-indigo-600 hover:text-indigo-500 font-medium"
                      @click="downloadBase64Image(standardPhotoUrl)"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                    </svg>
                    下载
                  </button>
                </div>
                <div class="aspect-w-3 aspect-h-4 bg-gray-100 rounded-lg overflow-hidden"
                     :style="{ backgroundColor: getBackgroundColor(selectedColor) }">
                  <div v-if="isLoading" class="flex items-center justify-center w-full h-full">
                    <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
                  </div>
                  <img v-else-if="standardPhotoUrl" :src="standardPhotoUrl" alt="标准证件照"
                       class="object-contain w-full h-full">
                </div>
              </div>
              <!-- 高清照 -->
              <div class="border-2 border-dashed border-gray-300 rounded-lg p-4">
                <div class="flex items-center justify-between mb-4">
                  <h3 class="text-lg font-medium text-gray-900">高清照</h3>
                  <button
                      class="inline-flex items-center text-sm text-indigo-600 hover:text-indigo-500 font-medium"
                      @click="downloadBase64Image(hdPhotoUrl)"
                  >
                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                    </svg>
                    下载
                  </button>
                </div>
                <div
                    class="aspect-w-3 aspect-h-4 rounded-lg overflow-hidden transition-colors duration-300"
                    :style="{ backgroundColor: getBackgroundColor(selectedColor) }"
                >
                  <div v-if="isLoading" class="flex items-center justify-center w-full h-full">
                    <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
                  </div>
                  <img v-else-if="hdPhotoUrl" :src="hdPhotoUrl" alt="高清证件照" class="object-contain w-full h-full">
                </div>
              </div>
            </div>

            <!-- 右侧：排版照 -->
            <div class="border-2 border-dashed border-gray-300 rounded-lg p-4">
              <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-medium text-gray-900">排版照</h3>
                <button
                    class="inline-flex items-center text-sm text-indigo-600 hover:text-indigo-500 font-medium"
                    @click="downloadBase64Image('')"
                >
                  <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                          d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4"/>
                  </svg>
                  下载
                </button>
              </div>
              <div class="aspect-w-3 aspect-h-4 rounded-lg overflow-hidden bg-gray-50 flex items-center justify-center">
                <div v-if="isLoading"
                     class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-500"></div>
                <div v-else class="text-gray-400 text-center p-8">
                  <!--                  <svg class="w-12 h-12 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">-->
                  <!--                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"-->
                  <!--                          d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>-->
                  <!--                  </svg>-->
                  <!--                  <p>排版照功能开发中</p>-->
                </div>
              </div>
            </div>
          </div>

          <!-- 第二栏：提示信息 -->
          <div class="p-4 bg-gray-50 rounded-lg">
            <div class="flex items-start">
              <svg class="w-5 h-5 text-gray-400 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
              </svg>
              <div class="ml-3">
                <p class="text-sm text-gray-600">
                  标准照适用于一般证件照使用场景，高清照适用于打印场景，可获得更好的打印效果。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 第四栏：生成按钮 -->
        <div class="flex justify-center mt-14 mb-8">
          <button
              class="bg-indigo-600 text-white py-4 px-12 rounded-lg font-medium hover:bg-indigo-500 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors duration-200 text-lg disabled:opacity-50 disabled:cursor-not-allowed"
              @click="generatePhoto"
              :disabled="isLoading || !uploadPhoto"
          >
            <span v-if="isLoading" class="flex items-center">
              <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none"
                   viewBox="0 0 24 24">
                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                <path class="opacity-75" fill="currentColor"
                      d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
              </svg>
              处理中...
            </span>
            <span v-else>生成证件照</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive} from 'vue'
import {useUserStore} from "@/stores/useUserStore";
import {
  DownloadIdPhotoRequest,
  downloadIdPhotoRequestByPost,
  ProduceIdPhotoRequest,
  produceIdPhotoRequestByPost
} from "@/api/picture-service";
import {message} from "@/plugins/message";
import {downloadImageBase64} from "@/utils";
import {useRouter} from "vue-router";

const userStore = useUserStore()
const router = useRouter()

// 状态定义
const isDragging = ref(false)
const uploadPhoto = ref<File>()
const previewUrl = ref('')
const selectedSize = ref<string>('1')
const selectedColor = ref('white')
const standardPhotoUrl = ref('https://img.picui.cn/free/2025/06/23/6858e18c9cb1c.png')
const hdPhotoUrl = ref('https://img.picui.cn/free/2025/06/23/6858e18c9cb1c.png')
const activeTab = ref('core')
const isLoading = ref(false)

// 证件照尺寸选项
const photoSizes = [
  {value: '1', label: '一寸（25×35mm）', dimensions: '25×35mm', width: 295, height: 413},
  {value: '2', label: '二寸（35×49mm）', dimensions: '35×49mm', width: 413, height: 579},
  {value: '3', label: '小一寸（22×32mm）', dimensions: '22×32mm', width: 260, height: 378},
  {value: '4', label: '大一寸（33×48mm）', dimensions: '33×48mm', width: 390, height: 567},
  {value: '5', label: '教师资格证（25×35mm）', dimensions: '25×35mm', width: 295, height: 413},
  {value: '6', label: '国家公务员（35×45mm）', dimensions: '35×45mm', width: 413, height: 531},
]

// 背景颜色选项
const backgroundColors = [
  {value: 'white', hexColor: '#ffffff', label: '白色'},
  {value: 'gray', hexColor: '#e5e7eb', label: '灰色'},
  {value: 'blue', hexColor: '#2563eb', label: '蓝色'},
  {value: 'darkBlue', hexColor: '#1e3a8a', label: '深蓝色'},
  {value: 'red', hexColor: '#dc2626', label: '红色'},
  {value: 'black', hexColor: '#000000', label: '黑色'}
]

// 高级参数
const advancedParams = reactive([
  {name: 'whiteningStrength', label: '美白强度', value: 0, min: 0, max: 15},
  {name: 'brightnessStrength', label: '亮度强度', value: 0, min: -5, max: 25},
  {name: 'contrastStrength', label: '对比度强度', value: 0, min: -10, max: 50},
  {name: 'saturationStrength', label: '饱和度强度', value: 0, min: -10, max: 50},
  {name: 'sharpenStrength', label: '锐化强度', value: 0, min: 0, max: 5}
])

// 文件处理方法
const handleFileChange = (e: Event) => {
  const target = e.target as HTMLInputElement
  if (target.files && target.files[0]) {
    const file = target.files[0]
    uploadPhoto.value = file
    handleFile(file)
  }
}

const handleDragOver = (e: DragEvent) => {
  isDragging.value = true
}

const handleDragLeave = (e: DragEvent) => {
  isDragging.value = false
}

const handleDrop = (e: DragEvent) => {
  isDragging.value = false
  if (e.dataTransfer?.files && e.dataTransfer.files[0]) {
    const file = e.dataTransfer.files[0]
    if (file.type.startsWith('image/')) {
      handleFile(file)
    }
  }
}

const handleFile = (file: File) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    if (e.target?.result) {
      previewUrl.value = e.target.result as string
    }
  }
  reader.readAsDataURL(file)
}

// 生成照片
const generatePhoto = async () => {

  if (!userStore.isLogin()) {
    message.warning('生成失败','请先登录')
    router.push({
      path:"/login"
    })
  }

  if (!uploadPhoto.value) {
    message.warning("生成失败", "请先上传");
    return;
  }

  isLoading.value = true;

  try {
    // 获取背景颜色
    let selectedPhotoSize = photoSizes[0]
    for (let photoSize of photoSizes) {
      if (selectedSize.value === photoSize.value) {
        selectedPhotoSize = photoSize
      }
    }
    // 封装请求体
    const produceIdPhotoRequest = {
      width: selectedPhotoSize.width,
      height: selectedPhotoSize.height,
      whiteningStrength:advancedParams[0].value,
      brightnessStrength:advancedParams[1].value,
      contrastStrength:advancedParams[2].value,
      saturationStrength:advancedParams[3].value,
      sharpenStrength:advancedParams[4].value
    } as ProduceIdPhotoRequest

    const res = await produceIdPhotoRequestByPost(uploadPhoto.value, produceIdPhotoRequest)
    if (res.code != 200) {
      message.error("生成失败", res.description || "");
      return;
    }

    standardPhotoUrl.value = res.data.image;
    hdPhotoUrl.value = res.data.imageHD;
  } catch (error) {
    console.error(error);
    message.error("生成失败，请重试", "");
  } finally {
    isLoading.value = false;
  }
}

const downloadBase64Image = async (base64: string) => {
  const downloadIdPhotoRequest = {
    color: getBackgroundColor(selectedColor.value),
    inputImageBase64: base64
  } as DownloadIdPhotoRequest

  const res = await downloadIdPhotoRequestByPost(downloadIdPhotoRequest)
  if (res.code != 200) {
    message.error("下载失败", res.description || "");
    return;
  }
  downloadImageBase64(res.data.imageBase64)
}

const clearPreview = () => {
  previewUrl.value = ''
}

// 获取背景颜色
const getBackgroundColor = (color) => {
  const colorObj = backgroundColors.find(c => c.value === color)
  return colorObj?.hexColor || '#e5e7eb'
}
</script>

<style scoped>
/* 自定义滑动条样式 */
input[type="range"] {
  appearance: none;
  background-color: #E5E7EB;
  height: 0.5rem;
  border-radius: 0.375rem;
}

input[type="range"]::-webkit-slider-thumb {
  appearance: none;
  width: 1rem;
  height: 1rem;
  background-color: #4F46E5;
  border-radius: 9999px;
  cursor: pointer;
  transition-property: background-color;
  transition-duration: 200ms;
}

input[type="range"]::-webkit-slider-thumb:hover {
  background-color: #6366F1;
}

input[type="range"]::-moz-range-thumb {
  appearance: none;
  width: 1rem;
  height: 1rem;
  background-color: #4F46E5;
  border-radius: 9999px;
  cursor: pointer;
  transition-property: background-color;
  transition-duration: 200ms;
  border: none;
}

input[type="range"]::-moz-range-thumb:hover {
  background-color: #6366F1;
}

/* 修复 Firefox 中的滑动条轨道样式 */
input[type="range"]::-moz-range-track {
  background-color: #E5E7EB;
  height: 0.5rem;
  border-radius: 0.375rem;
}
</style>